package com.cn.web.app.template.service;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cn.config.OrderConfig;
import com.cn.global.GlobalParamters;
import com.cn.global.GlobalParamtersUtil;
import com.cn.page.PageVo;
import com.cn.upload.base.FileItemEntity;
import com.cn.upload.config.UploadConfig;
import com.cn.user.UserDO;
import com.cn.util.DateUtil;
import com.cn.util.SnowflakeIdWorkerUtil;
import com.cn.web.app.baidu.BaiDuSdk;
import com.cn.web.app.baidu.FastDfsFileUpload;
import com.cn.web.app.template.entity.OrderTemplateEntity;
import com.cn.web.app.template.mapper.IOrderTemplateMapper;
import com.cn.web.app.template.vo.OrderTemplateListVO;
import com.cn.web.app.template.vo.OrderTemplateMarkEdit;
import com.cn.web.app.template.vo.OrderTemplateSearch;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderTemplateService {

    @Autowired
    private IOrderTemplateMapper orderTemplateMapper;

    @Autowired
    private OrderConfig orderConfig;

    @Autowired
    private BaiDuSdk baiDuSdk;

    @Autowired
    private UploadConfig uploadConfig;

    @Autowired
    private FastDfsFileUpload fastDfsFileUpload;

    public void edit(OrderTemplateEntity info, UserDO token) {
        if (info.getId() == null || info.getId() == 0) {
            info.setUserId(token.getId().toString());
            if (token.getOrgs() != null && token.getOrgs().size() > 0) {
                info.setOrgId(token.getOrgs().get(0).getId().toString());
            }
            if (token.getSuperFlag().equalsIgnoreCase("0")) {
                info.setTemplateType(0);
            } else {
                info.setTemplateType(1);
            }
            info.setCreateTime(DateUtil.getTime()).setId(SnowflakeIdWorkerUtil.getId());
            this.orderTemplateMapper.insert(info);
        } else {
            info.setUpdateTime(DateUtil.getTime());
            this.orderTemplateMapper.updateById(info);
        }

        //预处理
        try {
            preImg(info);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void del(String id) {
        this.orderTemplateMapper.deleteById(id);
    }

    public OrderTemplateEntity find(String id) {
        OrderTemplateEntity data = this.orderTemplateMapper.selectById(id);
        return data;
    }

    public OrderTemplateListVO findVO(String id) {
        QueryWrapper<OrderTemplateSearch> query = new QueryWrapper<>();
        query.eq("o1.id", id);
        List<OrderTemplateListVO> data = this.orderTemplateMapper.list(query);
        if (data == null || data.size() == 0) {
            return null;
        }
        return data.get(0);
    }

    public void approve(OrderTemplateEntity info) {
        OrderTemplateEntity data = this.find(info.getId().toString());
        if (data != null) {
            data.setApproveStatus(info.getApproveStatus()).setApproveNote(info.getApproveNote());
            this.orderTemplateMapper.updateById(data);
        }
    }

    public List<OrderTemplateListVO> list(OrderTemplateSearch search) {
        QueryWrapper<OrderTemplateSearch> query = new QueryWrapper<>();
        query.eq("1", 1);

        if (search != null) {
            if (StringUtils.isNotEmpty(search.getSearch())) {
                query.like("o1.template_name", search.getSearch());
            }
            if (search.getType() != null) {
                if (search.getType() == 1) {
                    //用户查询自己的
                    query.and(t -> {
                        t.eq("o1.user_id", search.getUserId())
                                .or().eq("o1.template_type", 0);
                    });
                } else if (search.getType() == 2) {
                    //组织机构查询本机构
                    query.and(t -> {
                        t.eq("o1.org_id", search.getOrgId())
                                .or().eq("o1.template_type", 0);
                    });
                }
            }
            if (search.getStatus() != null) {
                query.eq("o1.approve_status", search.getStatus());
            }

        }
        List<OrderTemplateListVO> data = this.orderTemplateMapper.list(query);
        return data;
    }

    public List<OrderTemplateListVO> listPage(OrderTemplateSearch search) {
        QueryWrapper<OrderTemplateSearch> query = new QueryWrapper<>();
        query.eq("1", 1);

        if (search != null) {
            if (StringUtils.isNotEmpty(search.getSearch())) {
                query.like("o1.template_name", search.getSearch());
            }
            if (search.getType() != null) {
                if (search.getType() == 1) {
                    //用户查询自己的
                    query.eq("o1.user_id", search.getUserId());
                } else if (search.getType() == 2) {
                    //组织机构查询本机构
                    query.eq("o1.org_id", search.getOrgId());
                }
            }
            if (search.getTemplateType() != null) {
                query.eq("o1.template_type", 0);
            }
            if (search.getStatus() != null) {
                query.eq("o1.approve_status", search.getStatus());
            }

        }
        List<OrderTemplateListVO> data = this.orderTemplateMapper.list(query);
        return data;
    }

    public PageInfo<OrderTemplateListVO> page(PageVo<OrderTemplateSearch> pageVo) {
        return PageHelper.startPage(pageVo.getPageNum(), pageVo.getPageSize()).doSelectPageInfo(() -> {
            listPage(pageVo.getParam());
        });
    }


    public void handle(OrderTemplateMarkEdit info) {
        OrderTemplateEntity data = this.find(info.getId().toString());
        if (data != null) {
            data.setBaiduTemplateId(info.getBaiduTemplateId()).setMarkStatus(1);
            this.orderTemplateMapper.updateById(data);
        }
    }

    /**
     * 预处理（处理失败后的补偿）
     */
    @Scheduled(cron = "0/30 * * * * ?")
    public void preTask() {
        QueryWrapper<OrderTemplateEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("approve_status", 0);
        List<OrderTemplateEntity> data = this.orderTemplateMapper.selectList(queryWrapper);
        for (OrderTemplateEntity t : data) {
            preImg(t);
        }
    }


    public void preImg(OrderTemplateEntity info) {
        GlobalParamters globalParamters = GlobalParamtersUtil.get();
        String dataDir = this.uploadConfig.getLocalUploadConfig().getDataDir();
//        File file = new File(dataDir + info.getTemplateUrl());

        //下载远程文件
        String urlPath = globalParamters.getFileDomain() + info.getTemplateUrl();
        log.error(urlPath);
        File file = HttpUtil.downloadFileFromUrl(urlPath, "/data/tmp");

        Map<String, Object> paramMap = new java.util.HashMap<>();
        paramMap.put("file", file);
        try {
            String domainUrl = this.orderConfig.getApiDomain() + "/files";
            String result = HttpUtil.post(domainUrl, paramMap);
            log.error("预处理返回结果：{}", result);
            JSONObject json = JSON.parseObject(result);

            int code = json.getInteger("code");
            if (code == 200) {
                JSONArray array = json.getJSONArray("data");
                String x = array.get(0).toString();
//                String[] tmp = x.split("base64,");
                String fileName = SnowflakeIdWorkerUtil.getId() + ".jpg";
                String filePath = dataDir + fileName;
                base64ToFile(filePath, x);

                //上传到fastdfs
                paramMap.put("file", new File(filePath));
                FileItemEntity fileItemEntity = this.fastDfsFileUpload.upload(paramMap);

                info.setTemplateUrl2(fileItemEntity.getUrl());
                info.setApproveStatus(1).setApproveNote("处理成功");
            } else {
                info.setApproveStatus(2).setApproveNote("预处理模板失败");
                log.error("预处理文件错误");
            }
            this.orderTemplateMapper.updateById(info);
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    public static void main(String[] args) {
        String filePath = "/data/2.jpg";
        String path = "http://dfs.xtgss.cn//2024-07-14/%E8%BA%AB%E4%BB%BD%E8%AF%81%E5%8F%8D%E9%9D%A2.jpg";
        Map<String, Object> paramMap = new java.util.HashMap<>();

        File file = HttpUtil.downloadFileFromUrl(path, "/data/tmp");
        paramMap.put("file", file);
        try {
            String result = HttpUtil.post("http://rec.xtgss.cn/files", paramMap);
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public static void base64ToFile(String absPath, String base64) {
        try {
            byte[] decodedBytes = Base64.decode(base64);
            Files.write(Paths.get(absPath), decodedBytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
